<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-11-20 10:16:02
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-12-04 10:31:28
-->
<template>
  <ActionTable :showBack="false" @addRow="showModal('ADD', { isOpen: 0 })" />
  <a-table
    :columns="columns"
    :row-key="(record) => record.id"
    :data-source="managerOfRole"
    :pagination="state.pagination"
    :loading="state.loading"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'isOpen'">
        <a-switch
          :checked="record.isOpen === 1"
          checked-children="开启"
          un-checked-children="关闭"
          @click="(checked) => showUserState(checked, record)"
        />
      </template>
      <template v-if="column.key === 'action'">
        <TableRowAction
          :showSelect="false"
          @updateItem="showModal('UPDATE', record)"
          @deleteItem="deleteRoleItem(record.id)"
        >
          <a-button class="btn-auth" type="primary" @click="setRoleAuth(record.id)"
            >权限</a-button
          >
        </TableRowAction>
      </template>
    </template>
  </a-table>
  <contextHolder />
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, h } from "vue";
import { TableProps, Modal, message as $message } from "ant-design-vue";
import RoleSchemas from "./roleSchemas.vue";
import RoleAuthSchemas from "./roleAuthSchemas.vue";
import { addRole, deleteRole, selectAllRole, updateRole } from "@/api/system/role";
import { paginationToQuery } from "@/utils/common";
import { modalTitleEnum } from "@/enums/modalEnum";
import { getAuthByRole, updateRoleAuth } from "@/api/system/role-auth";
const [modal, contextHolder] = Modal.useModal();
const childRef = ref();
const columns = [
  {
    dataIndex: "id",
    title: "ID",
    key: "id",
    align: "center",
  },
  {
    dataIndex: "roleName",
    title: "角色",
    key: "roleName",
    align: "center",
  },
  {
    dataIndex: "isOpen",
    title: "状态",
    key: "isOpen",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
  },
];
const state = reactive({
  loading: true,
  pagination: {
    pageSize: 10,
    current: 1,
    total: 0,
    showTotal: (total) => `总${total}条`,
  },
});
const managerOfRole = ref<API.RoleItem[]>();

/**
 * 获取数据
 */
const loadData = async () => {
  const { seachList, seachTotal } = await selectAllRole(
    paginationToQuery(state.pagination)
  );
  managerOfRole.value = seachList;
  state.pagination.total = seachTotal;
  state.loading = false;
};

/**
 * 更新管理员状态
 * @param checked
 * @param data
 */
const showUserState = async (checked, data) => {
  const { msg } = await updateRole({ id: data.id, isOpen: checked ? 1 : 0 });
  msg === "success" ? (loadData(), $message.success("设置成功")) : $message.error(msg);
};

/**
 * 切换分页
 * @param page
 */
const handleTableChange: TableProps["onChange"] = (page) => {
  state.pagination.current = page.current!;
  loadData();
};

/**
 * 删除角色
 * @param id
 */
const deleteRoleItem = async (id) => {
  const { msg } = await deleteRole({ id });
  msg === "success" ? (loadData(), $message.success("删除成功")) : $message.error(msg);
};

/**
 * 设置权限
 * @param id
 */
const setRoleAuth = async (roleId) => {
  const roleAuthResult = await getAuthByRole({ roleId });
  const roleAuthOfData = roleAuthResult ?? [];
  const roleAuthSlot = () =>
    h(RoleAuthSchemas, { ref: childRef, roleId, roleAuthOfData });
  modal.confirm({
    title: "设置角色权限",
    icon: null,
    width: 950,
    okText: "提交",
    cancelText: "取消",
    content: roleAuthSlot,
    async onOk() {
      const roleAuths = childRef.value.getRoleAuth();
      // const params = new URLSearchParams();
      // params.append('roleAuths', roleAuths);
      const { msg } = await updateRoleAuth(roleAuths);
      msg === "success"
        ? (loadData(), $message.success("设置成功"))
        : $message.error(msg);
    },
    onCancel() {
      Modal.destroyAll();
    },
  });
};

/**
 * 创建弹窗
 * @param type
 * @param data
 */
const showModal = (type: string, data?: any) => {
  const roleSchemasSlot = () => h(RoleSchemas, { ref: childRef, roleOfData: data });
  modal.confirm({
    title: modalTitleEnum[type] + "角色",
    icon: null,
    okText: "提交",
    cancelText: "取消",
    closable: true,
    content: roleSchemasSlot,
    async onOk() {
      const { id, roleName, isOpen } = childRef.value.formState;
      if (type === "ADD") {
        const { msg } = await addRole({ roleName, isOpen });
        msg === "success"
          ? (loadData(), $message.success("添加成功"))
          : $message.error(msg);
      } else if (type === "UPDATE") {
        const { msg } = await updateRole({ id, roleName, isOpen });
        msg === "success"
          ? (loadData(), $message.success("更新成功"))
          : $message.error(msg);
      }
    },
  });
};
onMounted(() => {
  loadData();
});
</script>
<style lang="less" scoped>
.btn-auth {
  margin-left: 10px;
}
</style>
